<template>
  <div>
    用户id<input v-model="userId">
    <button @click="addGroup">加入qq1群</button>
    <button @click="connect">连接ws</button>
    <button @click="sendMessage">Send</button>
    <button @click="close">Disconnect</button>

    <div v-if="messages.length">
      <p v-for="message in messages" :key="message">{{ message }}</p>
    </div>
    群聊<input v-model="msg"><button @click="sendGroup">发送群消息</button>
  </div>
  <button @click="createRoom">创建游戏房间</button>
</template>

<script>
export default {
  data() {
    return {
      resolve:null,
      msg: '',
      userId: 0,
      ws: null,
      messages: [],
      eventMap:{}
    };
  },
  methods: {
    connect() {
      //代表id为1的用户连接ws
      //把userId编程随机
      this.ws = new WebSocket(`ws://127.0.0.1:3000/chat?userId=${this.userId}`);

      this.ws.onopen = () => console.log('成功连接websocket服务');
      this.ws.onmessage = this.receiveMessage;
      this.ws.onclose = () => console.log('Disconnected');
    },
    addGroup(){
      let msg={
        from: this.userId,
        fn:'addGroup'
      };
      this.ws.send(JSON.stringify(msg));
    },
    async createRoom(){
      let msg={
        eventId: parseInt(Math.random()*1000),
        from: this.userId,
        fn:'createRoom'
      };
      console.log('this:',this)
       let rsp=await this.send(msg)
      alert('ws接口返回值：'+SON.stringify(rsp));
      //alert只能传一参数，console.log可以多个
    },
    send(msg){
      return new Promise((resolve, reject) => {
        this.ws.send(JSON.stringify(msg))
        console.log(1)
        this.eventMap[msg.eventId] = resolve
      });
    },
    sendGroup(){
      let msg={
        from: this.userId,
        fn:'sendGroup',
        msg:this.msg
      };
      this.ws.send(JSON.stringify(msg));
    },
    sendMessage() {
      if (this.ws) {
        let msg={
          from: this.userId,
          to: 2,
          data:'360你好我是ie浏览器'
        };
        this.ws.send(JSON.stringify(msg));
      }
    },
    receiveMessage(event) {
      console.log('客户端收到消息：',event.data)
      let msg=JSON.parse(event.data)
      //通过事件驱动eventId获取promise的回调
      let resolve=this.eventMap[msg.eventId];
      console.log('事件驱动集合:',this.eventMap);
      console.log('msg.eventId:',msg.eventId);
      console.log('resolve:',resolve);
      //通过回调激活pending状态的promise，await就能收到消息了
      resolve('success')
      this.eventMap[msg.eventId]=null
    },
    close() {
      if (this.ws) {
        this.ws.close();
      }
    }
  },
  mounted() {
    this.connect();
  },
  beforeDestroy() {
    this.close();
  }
};
</script>